package com.tt.utils.wordUtils.renderplicy;

import com.deepoove.poi.data.style.BorderStyle;
import com.deepoove.poi.data.style.TableStyle;
import com.deepoove.poi.policy.AbstractRenderPolicy;
import com.deepoove.poi.render.RenderContext;
import com.deepoove.poi.util.TableTools;
import com.deepoove.poi.xwpf.BodyContainer;
import com.deepoove.poi.xwpf.BodyContainerFactory;
import com.tt.utils.wordUtils.entity.TableContent;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.util.List;


/**
 * @Title: TableRenderPolicy
 * @Author zl
 * @Package com.oberyun.goHAZOP.utils.wordUtils
 * @Date 2025/9/4 18:07
 * @description: 表格渲染（支持动态表头）
 */
public class TableRenderV2Policy extends AbstractRenderPolicy<TableContent.TableBody> {

    @Override
    protected boolean validate(TableContent.TableBody data) {
        return data != null;
    }

    @Override
    protected void afterRender(RenderContext<TableContent.TableBody> context) {
        clearPlaceholder(context, true);
    }

    @Override
    public void doRender(RenderContext<TableContent.TableBody> context) throws Exception {
        TableContent.TableBody data = context.getData();
        //添加表头
        XWPFRun run = context.getRun();
        XWPFTable table = createTable(run,4,4);
        List<XWPFTableRow> rows = table.getRows();
        for (int i = 0; i < rows.size(); i++) {
            XWPFTableRow row = rows.get(i);
            for (int j = 0; j < row.getTableCells().size(); j++) {
                XWPFTableCell cell = row.getCell(j);
                // 设置垂直居中
                cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                setCellHorizontalAlignment(cell, STJc.CENTER);
                cell.setText("cshi"+j);
            }
        }
        TableTools.mergeCellsHorizonal(table, 0, 1, 2);
//        TableTools.mergeCellsVertically(table, 0, 0, 1);
    }

    /**
     * 创建表格
     */
    public XWPFTable createTable(XWPFRun run,Integer rowNum,Integer cellNum) {
        BodyContainer bodyContainer = BodyContainerFactory.getBodyContainer(run);
        BodyType partType = bodyContainer.getTarget().getPartType();
        XWPFTable xwpfTable = null;
        if(partType == BodyType.TABLECELL){
            XWPFParagraph paragraph = (XWPFParagraph) run.getParent();
            XWPFTableCell templateCell = (XWPFTableCell) paragraph.getBody();
            xwpfTable = templateCell.getTableRow().getTable();
            for (int i = 0; i < rowNum; i++) {
                xwpfTable.createRow();
            }
        }else{
            xwpfTable = bodyContainer.insertNewTable(run, rowNum, cellNum);
            setTableStyle(xwpfTable);
            setCellHorizontalAlignment(xwpfTable, STJc.CENTER);
        }
        return xwpfTable;
    }

    /**
     * 设置单元格水平对齐方式
     */
    private void setCellHorizontalAlignment(XWPFTable newTable, STJc.Enum alignment) {
        List<XWPFTableRow> rows = newTable.getRows();
        if (rows.size() > 0) {
            for (XWPFTableRow row : rows) {
                List<XWPFTableCell> cells = row.getTableCells();
                for (XWPFTableCell cell : cells) {
                    XWPFParagraph paragraph = cell.getParagraphs().get(0);
                    CTP ctp = paragraph.getCTP();
                    CTPPr ppr = ctp.isSetPPr() ? ctp.getPPr() : ctp.addNewPPr();
                    CTJc jc = ppr.isSetJc() ? ppr.getJc() : ppr.addNewJc();
                    jc.setVal(alignment);
                }
            }
        }
    }

    /**
     * 设置单元格水平对齐方式
     */
    private void setCellHorizontalAlignment(XWPFTableCell cell, STJc.Enum alignment) {
        if (cell.getParagraphs().size() > 0) {
            XWPFParagraph paragraph = cell.getParagraphs().get(0);
            CTP ctp = paragraph.getCTP();
            CTPPr ppr = ctp.isSetPPr() ? ctp.getPPr() : ctp.addNewPPr();
            CTJc jc = ppr.isSetJc() ? ppr.getJc() : ppr.addNewJc();
            jc.setVal(alignment);
        }
    }

    /**
     * 设置表格样式
     * @param newTable
     */
    private void setTableStyle(XWPFTable newTable) {
        BorderStyle build = BorderStyle.builder()
                .withColor("000000")   // 黑色
                .withSize(4)           // 边框粗细（单位 1/8 pt, 4=0.5pt）
                .withType(XWPFTable.XWPFBorderType.SINGLE)  // 单实线
                .build();
        TableTools.setBorder(newTable::setTopBorder, build);
        TableTools.setBorder(newTable::setBottomBorder, build);
        TableTools.setBorder(newTable::setLeftBorder, build);
        TableTools.setBorder(newTable::setRightBorder, build);
        TableTools.setBorder(newTable::setInsideHBorder, build); // 内部横线
        TableTools.setBorder(newTable::setInsideVBorder, build); // 内部竖线
        // 设置表格宽度 100%
        TableStyle tableStyle = new TableStyle();
        tableStyle.setWidth("100%");
        tableStyle.setAlign(TableRowAlign.CENTER);
        TableTools.styleTable(newTable, tableStyle);
    }

}
